package com.sigmatrix.h5.blob;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.RetryExponentialRetry;
import com.microsoft.azure.storage.blob.BlobRequestOptions;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;

import so.sao.file.datastore.service.FileService;

@Configuration
@EnableConfigurationProperties(AzureBlobProperties.class)
@ConditionalOnProperty(value = "sao.azure.connectionString")
@ConditionalOnClass(FileService.class)
public class AzureBlobConfiguration {

    @Autowired
    private AzureBlobProperties azureBlobProperties;

    /**
     * 读取配置文件Azure blob信息，初始化blob container
     */
    @RefreshScope
    @Bean
    public Map<String, CloudBlobContainer> blobContainerMap() throws Exception {

        CloudStorageAccount cloudStorageAccount = CloudStorageAccount.parse(azureBlobProperties.getConnectionString());
        CloudBlobClient cloudBlobClient = cloudStorageAccount.createCloudBlobClient();
        cloudBlobClient.setDefaultRequestOptions(createBlobRequestOptions());

        Map<String, CloudBlobContainer> map = new ConcurrentHashMap<>();
        for (String containerName : azureBlobProperties.getContainerNames()) {

            CloudBlobContainer container = cloudBlobClient.getContainerReference(containerName);
            if (!container.exists()) {
                throw new Exception("指定的containerName : " + containerName + " 不存在。");
            }
            map.put(containerName, container);
        }

        return map;
    }

    @Bean
    public AzureCloudFileService fileService() {
        return new AzureCloudFileService();
    }

    private BlobRequestOptions createBlobRequestOptions() {

        BlobRequestOptions blobRequestOptions = new BlobRequestOptions();
        blobRequestOptions.setDisableContentMD5Validation(true);
        blobRequestOptions.setStoreBlobContentMD5(false);
        blobRequestOptions.setRetryPolicyFactory(new RetryExponentialRetry());
        blobRequestOptions.setUseTransactionalContentMD5(false);

        return blobRequestOptions;
    }
}
